package linkedlist.test382;

import listbyorder.utils.ListNode;

import java.util.Random;

/**
 * @author code_yc
 * @version 1.0
 * @date 2020/7/15 12:40
 */
public class Solution1 {

    public class ListNode {
        int val;
        ListNode next;

        ListNode(int x) {
            val = x;
        }
    }

    int l = 0;
    ListNode head;

    /**
     * @param head The linked list's head.
     *             Note that the head is guaranteed to be not null, so it contains at least one node.
     */
    public Solution1(ListNode head) {
        this.head = head;
        ListNode t = head;
        while (t != null) {
            l++;
            t = t.next;
        }
    }

    /**
     * Returns a random node's value.
     */
    public int getRandom() {
        int c = new Random().nextInt(l);
        ListNode t = head;
        while (c-- != 0) {
            t = t.next;
        }
        return t.val;
    }
}
